package cn.itcast.security;

import cn.itcast.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class UserService implements UserDetailsService {
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 根据用户名加载用户信息
     * @params
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //模拟数据库中的用户数据
        Map<String, Object> map = new HashMap<>();
        User user1 = new User();
        user1.setUsername("admin");
        user1.setPassword(passwordEncoder.encode("admin"));

        User user2 = new User();
        user2.setUsername("xiaoming");
        user2.setPassword(passwordEncoder.encode("1234"));
        map.put(user1.getUsername(), user1);
        map.put(user2.getUsername(), user2);
        User user = (User) map.get(username);//模拟根据用户名查询数据库
        if (ObjectUtils.isEmpty(user)) {
            //根据用户名没有查询到用户
            return null;
        }
        //模拟数据库中的密码，后期需要查询数据库
        String passwordInDb = user.getPassword();
        ArrayList<GrantedAuthority> list = new ArrayList<>();

        //如果是普通字符串默认为权限，如果是以ROLE_开头默认为角色
        if ("admin".equals(user.getUsername())) {

            list.add(new SimpleGrantedAuthority("add"));
        }
        list.add(new SimpleGrantedAuthority("delete"));
        list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        org.springframework.security.core.userdetails.User user3 = new org.springframework.security.core.userdetails.User(username, passwordInDb, list);
        return user3;
    }
}
